package controllers

import (
	"errmsg"
	"fmt"
	"github.com/astaxie/beego/logs"
	"io/ioutil"
	"net/http"
	"smart_home/api/device"
	"smart_home/api/models"
	"smart_home/api/utils/mqtt"
	"strings"
	"tools"
)

type MqttController struct {
	BaseController
}

//@Title mqtt auth
//@Description mqtt权限认证
//@router /auth [post]
func (c *MqttController) Auth() {
	var (
		cid   string
		uname string
		pwd   string
		user  *models.User
		err   error
		eq    *models.Equipment
	)

	logs.Debug("mqtt params:", c.Input())

	cid = c.GetString("clientid")
	uname = c.GetString("username")
	pwd = c.GetString("password")

	if len(cid) > 0 && mqtt.IsOnline(cid) {
		logs.Error("mqtt repeat login:", cid)
		c.noAuth()
		return
	}

	if uname == "server" && pwd == "123456" {
		return
	}

	if uname == "equipment" {
		if eq, err = models.GetEquipmentBySta(cid); err == nil && eq != nil && eq.Password == pwd {
			topic := fmt.Sprintf("app/equipment/%s/connect", cid)
			err = mqtt.Push(topic, "connect", 1, true)
			if err != nil {
				logs.Error("equipment connect push err:", err)
			}
			return
		}
	}

	if uname == "app" {
		if cid = strings.Split(cid, "_")[0]; len(cid) > 0 {
			if user, err = models.GetUserById(cid); err == nil && user != nil && user.Password == tools.MD5Encode(pwd) {
				logs.Debug("match user:", user)
				return
			}
		}
	}

	c.noAuth()
}

//@Title mqtt superuser
//@Description mqtt权限认证
//@router /superuser [post]
func (c *MqttController) Superuser() {
	//fmt.Println(c.Input())
}

//@Title mqtt superuser
//@Description mqtt权限认证
//@router /acl [get]
func (c *MqttController) Acl() {
	fmt.Println("input:", c.Input())
	fmt.Println("body:", c.Ctx.Input.RequestBody)
}

//@Title mqtt command confirm
//@Description mqtt 命令确认
//@router /confirm [post]
func (c *MqttController) Confirm() {
	// body 传送 rsa + base64 加密
	bytes, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		c.Error(err)
		return
	}

	// 发送完成信号
	device.SendSign(string(bytes))
	c.Success(nil)
}

//@Title mqtt get user info
//@Description mqtt mqtt 获取用户信息
//@router /user [get]
func (c *MqttController) User() {
	var (
		userName string
		clientId string
		err      error
		user     *models.User
		eq       *models.Equipment
	)
	userName = c.GetString("username")
	clientId = c.GetString("client_id")

	if userName == "app" {
		if user, err = models.GetUserById(clientId); err == nil && user != nil {
			c.Success(user)
			return
		}
	}

	if userName == "equipment" {
		if eq, err = models.GetEquipmentBySta(clientId); err == nil && eq != nil {
			c.Success(eq.User)
			return
		}
	}

	c.Error(errmsg.ErrResponseNotFound)
}

//@Title 设备操作日志
//@Description mqtt mqtt 获取用户信息
//@router /equipment_log [post]
func (c *MqttController) EquipmentLog() {
	var (
		sta string
		act int
		err error
	)
	sta = c.GetString("sta")
	if act, err = c.GetInt("act", 0); err != nil {
		logs.Error("MqttController error:", err)
		c.Error(errmsg.ErrResponseParameter)
		return
	}

	if err = models.AddEquipmentLog(sta, act); err != nil {
		c.Error(err)
		return
	}

	c.Success(nil)
}

func (c *MqttController) noAuth() {
	http.Error(c.Ctx.ResponseWriter, "Permission dend", 405)
}
